<script setup>
import {useRouter} from "vue-router";
import * as Auth from "@/utils/auth.js";
import {getUserDetailList, tokenInfo} from "@/api/user.js";
import {onUpdated, ref} from "vue";
import {getUserLocal, setUserLocal} from "@/utils/auth.js";
import Refresh from "@/components/refresh.vue";

const orderQuantity = ref(0)

const login = ref(false)
const user = ref({})

const router = useRouter();

function fresh() {
  if (Auth.getTokenLocal()) {
    const token = {
      token: Auth.getTokenLocal()
    };
    const email = {
      email: Auth.getUserLocal().email
    };
    tokenInfo(token).then(result => {
      console.log(result)
      if (result.data.data.isLogin === true) {
        login.value = true
        getUserDetailList(email).then(result => {
          setUserLocal(result.data.data)

        })
        user.value = getUserLocal()
      } else {
        // logout()
      }
    })
  } else {
    console.log('没有token')
  }
}

function logout() {
  Auth.removeTokenLocal()
  Auth.removeUserLocal()
  login.value = false
}

onUpdated(() => {
  fresh()
  console.log('updated')
})
fresh()
</script>

<template>
  <refresh @onRefreshItem="fresh">
    <div class="user" v-show="login">
      <div style="padding: 10px 0" @click="$router.push('/profile')">
        <van-image height="8vh" width="8vh" :src="user.avatar" round style="padding-left: 10px" fit="cover"/>
        <span class="item_u">{{ user.uname }}</span>
      </div>
    </div>
    <div class="user" @click="$router.push('/login/user')" v-show="!login">
      <div style="padding: 10px 0">
        <van-image height="8vh" width="8vh" src="/vite.svg" round style="padding-left: 10px" fit="cover"/>
        <span class="item_u">请登录</span>
      </div>
    </div>

    <div>
      <van-grid :border="false">
        <van-grid-item icon="goods-collect-o" @click="$router.push('/collection')" text="想要"/>
        <van-grid-item icon="logistics" @click="$router.push('/address')" text="地址"/>
        <van-grid-item icon="eye-o" text="足迹"/>
        <van-grid-item icon="add-o" text="订阅"/>
      </van-grid>
    </div>
    <div>
      <van-cell-group inset id="order">
        <van-cell title="订单" :value="orderQuantity" is-link>
        </van-cell>
        <van-cell title="钱包" :value="orderQuantity" is-link/>
        <van-cell title="客服" is-link/>
        <van-cell icon="delete-o" title="退出登录" @click="logout" v-show="login"/>
      </van-cell-group>
    </div>
  </refresh>
</template>

<style lang="less" scoped>
.user {
  position: relative;
  background-color: #fafafa;
  border: 26px solid #fff;
  border-radius: 40px;

  .item_u {
    display: inline-block;
    font-size: 20px;
    font-weight: bold;
    line-height: 8vh;
    height: 8vh;
    position: absolute;
    top: 6%;
    padding-left: 14px;
  }

}

van-grid-item {
  deep(.van-grid-item__content--center) {
  background-color: #fafafa;
}
}

#order .van-cell {
  background-color: #fafafa;

}
</style>
